package com.group9.handinhand.social;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UserProfile;

import com.group9.handinhand.service.UserService;
import com.group9.handinhand.service.so.UserSO;
import com.group9.handinhand.utils.HandInHandSecureRandom;

public class SocialConnectionSignUp implements ConnectionSignUp {
	
	@Autowired
	UserService userService;	

	@Override
	public String execute(Connection<?> connection) {
		UserProfile userProfile = connection.fetchUserProfile();
		String email = userProfile.getEmail();
		
		if(email == null) {
			return null;
		}
		
		UserSO user = null;
		user = userService.getUserByEmail(email);
		if(user != null)
			return user.getEmail();
		
		user = new UserSO();
		user.setEmail(email);
		user.setName(userProfile.getFirstName());
		user.setSurname(userProfile.getLastName());
		user.setUsername(connection.getKey().getProviderId() + ":" + connection.getKey().getProviderUserId());
		user.setPassword(new HandInHandSecureRandom().nextRandomPassword());
		
		user = userService.registerUser(user);
		
		if(user != null)
			return user.getEmail();
		
		return null;
	}

}
